﻿using EMoney.IStock.Client.DataAccess.MC;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models.MC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EMoney.IStock.Client.Business.MC
{
    /// <summary>
    /// 任务信息业务处理类
    /// </summary>
    public class TaskInfoBll
    {
        private object objTaskInfo = new object();

        private const string TASKINFO_MEMCACHED_KEY = "EMoney.IStock.Client.Business.MC.TaskInfoBll.TaskInfo";

        /// <summary>
        /// 获取任务信息列表
        /// </summary>
        /// <returns></returns>
        public List<MC_TaskInfo> GetTaskInfoList()
        {
            List<MC_TaskInfo> list = CacheManager.RedisCache.Get<List<MC_TaskInfo>>(TASKINFO_MEMCACHED_KEY);

            if (list == null)
            {
                try
                {
                    lock (objTaskInfo)
                    {
                        list = CacheManager.RedisCache.Get<List<MC_TaskInfo>>(TASKINFO_MEMCACHED_KEY);

                        if (list == null)
                        {
                            TaskInfoDal taskInfoDal = new TaskInfoDal();

                            list = taskInfoDal.GetTaskInfoList();

                            if (list == null)
                            {
                                list = new List<MC_TaskInfo>();
                            }

                            if (list != null && list.Count > 0)
                            {
                                TaskConditionBll taskConditionBll = new TaskConditionBll();

                                List<MC_TaskCondition> listCondition = taskConditionBll.GetTaskConditionList();

                                foreach (MC_TaskInfo task in list)
                                {
                                    if (listCondition != null && listCondition.Count > 0)
                                    {
                                        task.TaskConditionList = listCondition.FindAll(lst => lst.TaskID == task.TaskID);
                                    }
                                }
                            }

                            CacheManager.RedisCache.Set<List<MC_TaskInfo>>(TASKINFO_MEMCACHED_KEY, list);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "获取任务信息列表失败");
                }
            }

            return list;
        }

        /// <summary>
        /// 完成连登任务
        /// </summary>
        /// <param name="myInfo"></param>
        /// <returns></returns>
        public void CompleteContinueLoginTask(MC_MyInfo myInfo)
        {
            if (myInfo != null)
            {
                bool flag = false;
                DateTime dtNow = DateTime.Now;

                try
                {
                    ContinueLoginDal continueLoginDal = new ContinueLoginDal();

                    MC_ContinueLogin continueLogin = continueLoginDal.GetContinueLogin(myInfo.UserID);

                    if (continueLogin == null)  //第一次完成连登任务
                    {
                        continueLogin = new MC_ContinueLogin() {
                            LoginDate = dtNow.Date,
                            LoginDays = 1,
                            UpdateTime = dtNow,
                            UserID = myInfo.UserID
                        };

                        if (continueLoginDal.AddContinueLogin(continueLogin) == 1)
                        {
                            flag = true;
                        }
                    }
                    else
                    {
                        if (continueLogin.LoginDate != dtNow.Date)  //今日未完成连登任务
                        {
                            if (continueLogin.LoginDate != dtNow.AddDays(-1).Date)   //昨天未登录
                            {
                                continueLogin.LoginDays = 1;
                            }
                            else    //昨天登录
                            {
                                if (continueLogin.LoginDays >= 5)   //已连登5天，重新计算奖励的i豆
                                {
                                    continueLogin.LoginDays = 1;
                                }
                                else
                                {
                                    continueLogin.LoginDays++;
                                }
                            }

                            continueLogin.LoginDate = dtNow.Date;
                            continueLogin.UpdateTime = dtNow;

                            if (continueLoginDal.UpdateContinueLogin(continueLogin) >= 1)   //更新连登记录
                            {
                                flag = true;
                            }
                        }
                    }

                    if (flag)
                    {
                        myInfo.ContinueLoginDays = continueLogin.LoginDays;

                        CompleteTask(myInfo, MC_TaskID.ContinueLogin.GetHashCode(), StringHelper.GetContinueLoginINum(continueLogin.LoginDays));
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, string.Concat("完成连登任务失败.",myInfo.UserID));
                }
            }
        }

        /// <summary>
        /// 完成任务
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="taskid"></param>
        public bool CompleteTask(MC_MyInfo myinfo, int taskid,int iNum = 0)
        {
            bool flag = false;

            if (myinfo == null)
            {
                return flag;
            }

            List<MC_TaskInfo> taskList = GetTaskInfoList(); //获取任务列表

            if (taskList != null && taskList.Count > 0)
            {
                MC_TaskInfo taskInfo = taskList.Find(task => task.TaskID == taskid);    //获取指定任务

                if (taskInfo != null)
                {
                    try
                    {
                        DateTime dtNow = DateTime.Now;
                        ILevelInfoBll iLevelInfoBll = new ILevelInfoBll();
                        CompleteTaskRecordDal completeTaskRecordDal = new CompleteTaskRecordDal();

                        MC_CompleteTaskRecord record = new MC_CompleteTaskRecord()
                        {
                            UserID = myinfo.UserID,
                            TaskID = taskid,
                            CompleteDate = dtNow.Date
                        };

                        if (taskInfo.Type == MC_TaskType.Single.GetHashCode())  //一次性任务
                        {
                            if (completeTaskRecordDal.GetCompleteTaskRecord(myinfo.UserID, taskid) > 0) //已完成该一次性任务
                            {
                                return flag;
                            }
                        }
                        else
                        {
                            if (completeTaskRecordDal.GetCompleteTaskRecord(record) > 0)    //今日已完成该任务
                            {
                                return flag;
                            }
                        }

                        //if (myinfo.TodayCompleteTaskRecord != null && myinfo.TodayCompleteTaskRecord.Count > 0)
                        //{
                        //    if (myinfo.TodayCompleteTaskRecord.Find(today => today.TaskID == taskInfo.TaskID) != null)  //今日已完成该任务
                        //    {
                        //        return flag;
                        //    }
                        //}

                        if (iNum > 0)   //使用传入的i豆数量作为该任务的奖励
                        {
                            taskInfo.iNum = iNum;
                        }                        

                        int newINum = myinfo.iNum + taskInfo.iNum;  //完成该任务后用户总的i豆数量

                        MC_ILevelInfo iLevelInfo = iLevelInfoBll.GetILevelInfo(newINum);    //完成该任务后拥有的i豆数量等级

                        if (iLevelInfo != null)
                        {
                            record.iNum = taskInfo.iNum;
                            record.RecordTime = dtNow;

                            if (completeTaskRecordDal.AddCompleteTaskRecord(record) == 1)    //完成任务记录添加成功
                            {
                                myinfo.iNum = newINum;
                                MyInfoBll myInfoBll = new MyInfoBll();

                                if (iLevelInfo.LevelID != myinfo.Level)
                                {
                                    myinfo.NextLeveliNum = myInfoBll.GetNextLeveliNum(iLevelInfo.LevelID);  //获取下一等级i豆数量
                                }

                                myinfo.Level = iLevelInfo.LevelID;
                                myinfo.UpdateTime = dtNow;
                                myinfo.TaskDate = dtNow.Date;

                                switch ((MC_TaskType)taskInfo.Type)
                                {
                                    case MC_TaskType.Single:
                                        if (myinfo.CompletedSingleTaskID == null)
                                        {
                                            myinfo.CompletedSingleTaskID = new Dictionary<int, DateTime>();
                                        }

                                        if (!myinfo.CompletedSingleTaskID.ContainsKey(taskInfo.TaskID))
                                        {
                                            myinfo.CompletedSingleTaskID.Add(taskInfo.TaskID, dtNow);  //添加已完成任务编号
                                        }
                                        break;
                                    case MC_TaskType.Daily:
                                        if (myinfo.CompletedDailyTaskID == null)
                                        {
                                            myinfo.CompletedDailyTaskID = new Dictionary<int, DateTime>();
                                        }

                                        if (!myinfo.CompletedDailyTaskID.ContainsKey(taskInfo.TaskID))
                                        {
                                            myinfo.CompletedDailyTaskID.Add(taskInfo.TaskID, dtNow);  //添加已完成任务编号
                                        }
                                        break;
                                    default:
                                        break;
                                }

                                if (myinfo.TodayCompleteTaskRecord == null)
                                {
                                    myinfo.TodayCompleteTaskRecord = new List<MC_CompleteTaskRecord>();
                                }

                                if (myinfo.TodayCompleteTaskRecord.Find(today => today.TaskID == taskInfo.TaskID) == null)
                                {
                                    myinfo.TodayCompleteTaskRecord.Add(record); //添加今日完成任务记录属性
                                }

                                MyInfoDal myInfoDal = new MyInfoDal();

                                myInfoDal.UpdateMyInfo(myinfo); //更新个人信息
                                myInfoBll.SetMyInfo(myinfo);    //更新个人信息缓存

                                myinfo.TaskInfo = taskInfo;     //记录本次完成的任务信息

                                flag = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.DefaultLogger.Error(ex, string.Concat("完成任务失败.", myinfo.UserID, ".", taskid));
                    }                    
                }
            }

            return flag;
        }

        /// <summary>
        /// 获取用户今日完成的任务数量及获得的i豆数量
        /// </summary>
        /// <param name="myInfo"></param>
        /// <param name="todayCount"></param>
        /// <param name="todayINum"></param>
        public void GetTodayCompletedCountAndINum(MC_MyInfo myInfo, out int todayCount, out int todayINum)
        {
            todayCount = 0;
            todayINum = 0;

            if (myInfo != null && myInfo.TodayCompleteTaskRecord != null && myInfo.TodayCompleteTaskRecord.Count > 0)
            {
                DateTime dtNow = DateTime.Now;

                foreach (MC_CompleteTaskRecord record in myInfo.TodayCompleteTaskRecord)    //今日完成任务记录
                {
                    if (record.CompleteDate == dtNow.Date)
                    {
                        todayCount++;
                        todayINum += record.iNum;
                    }
                }
            }
        }

        /// <summary>
        /// 获取用户完成的任务信息列表
        /// </summary>
        /// <param name="myInfo"></param>
        /// <param name="flag">1：完成 0：未完成</param>
        /// <returns></returns>
        public List<MC_TaskInfo> GetUserTaskInfoList(MC_MyInfo myInfo,int flag)
        {
            List<MC_TaskInfo> retTaskInfoList = new List<MC_TaskInfo>();

            if (myInfo != null)
            {
                Dictionary<int, DateTime> completedTaskID = myInfo.CompletedSingleTaskID;   //已完成的单次任务编号列表

                if (completedTaskID == null)
                {
                    completedTaskID = new Dictionary<int, DateTime>();
                }

                if (myInfo.CompletedDailyTaskID != null && myInfo.CompletedDailyTaskID.Count > 0)    //已完成的日常任务编号列表
                {
                    foreach (KeyValuePair<int, DateTime> item in myInfo.CompletedDailyTaskID)
                    {
                        if (!completedTaskID.ContainsKey(item.Key))
                        {
                            completedTaskID.Add(item.Key, item.Value);
                        }
                    }
                }

                TaskInfoBll taskInfoBll = new TaskInfoBll();

                List<MC_TaskInfo> taskInfoList = taskInfoBll.GetTaskInfoList();

                if (taskInfoList != null && taskInfoList.Count > 0)
                {
                    foreach (MC_TaskInfo task in taskInfoList)
                    {
                        switch (flag)
                        {
                            case 1:     //完成
                                if (completedTaskID.ContainsKey(task.TaskID))
                                {
                                    task.CompletedTime = completedTaskID[task.TaskID];

                                    retTaskInfoList.Add(task);
                                }
                                break;
                            case 0:     //未完成
                                if (!completedTaskID.ContainsKey(task.TaskID))
                                {
                                    retTaskInfoList.Add(task);
                                }
                                break;
                            default:
                                break;
                        }                        
                    }
                }
            }

            return retTaskInfoList;
        }
    }
}
